package view;

import java.rmi.RemoteException;

import javax.swing.JComboBox;
import javax.swing.JFrame;

import server.FirewallException;
import server.NotExpertException;
import server.ReadWriteException;

import controller.FirewallSession;

public class RulesetDeleteFrame extends AbstractTextFieldFrame
{
	/**
	 * Serial version ID - for serialization
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * The combo box which displayed.
	 */
	private static JComboBox deleteField = null;
	
	/**
	 * Server controller
	 */
	protected FirewallSession UI;
	
	public RulesetDeleteFrame(FirewallSession UI)
	{
	    super("Ruleset", "Delete Ruleset:");
	    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	    this.UI = UI;

	    try{
		    /* Combobox for inserting integer */
	    	deleteField = new JComboBox(UI.getRuleSets());
	   }  catch (RemoteException e1) {
			ErrorFrame.AddError("Failed to delete the rule:" + e1.getMessage(), new JFrame());
		} catch (FirewallException e1) {
			ErrorFrame.AddError("Failed to delete the rule:" + e1.getMessage(), new JFrame());
		} 
		
		addDataField(deleteField);
		setLocationRelativeTo(null);
	}


	/**
	 * Action performed by finish button press:
	 * delte the selected ruleset if it's not the active ruleset
	 * if it's current displayed ruleset - load the default
	 */
	protected void finishAction()
	{
		/* Get the ruleset name */
		String rulesetToDel = (String)deleteField.getSelectedItem();
		
		if(rulesetToDel.equals(Settings.ruleset)) 
		{
			ErrorFrame.AddError("Current ruleset can't be deleted.", this);
			return;
		}

		try {
			String activeRuleset = UI.getCurrentRuleSet();
			
			if(rulesetToDel.equals(activeRuleset))
			{
				ErrorFrame.AddError("Active ruleset can't be deleted.", this);
				return;				
			}
		} catch (RemoteException e){
			ErrorFrame.AddError("RMI connection problems: ruleset can't be deleted", this);
			return;
		}
		
		try {
			UI.deleteRuleSet(rulesetToDel);
		} catch (RemoteException e) {
			ErrorFrame.AddError("RMI connection problems: ruleset can't be deleted",this);
		} catch (FirewallException e) {
			ErrorFrame.AddError(e.getMessage(),this);
		} catch (ReadWriteException e) {
			ErrorFrame.AddError(e.getMessage(),this);
		} catch (NotExpertException e) {
			ErrorFrame.AddError(e.getMessage(),this);
		}
		dispose();
	}

}
